class Solution {
public:
    string removeDuplicateLetters(string s) 
    {
        vector<int> numOfAlpha(26, 0), IsVisited(26, 0);
        for (size_t i = 0; i < s.size(); i++)
        {
            numOfAlpha[s[i] - 'a']++;
        }

        string ret;
        for (size_t i = 0; i < s.size(); i++)
        {
            char ch = s[i];
            if (!IsVisited[s[i] - 'a'])     // 没有被访问
            { 
                while (!ret.empty() && ret.back() > ch)
                {
                    if (numOfAlpha[ret.back() - 'a'])
                    {
                        IsVisited[ret.back()- 'a'] = 0;
                        ret.pop_back();
                    }
                    else
                    {
                        break;
                    }
                }
                ret.push_back(ch);
                IsVisited[s[i] - 'a'] = 1;
            }
           
            numOfAlpha[ch - 'a']--;
        }

        return ret;
    }
};